package com.kaikeba.t31.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.google.common.collect.Lists;
import com.kaikeba.t31.admin.po.AdminRoleMenu;
import com.kaikeba.t31.admin.po.AdminRoleUser;
import com.kaikeba.t31.admin.po.Menu;
import com.kaikeba.t31.core.service.impl.CrudServiceImpl;
import com.kaikeba.t31.dao.MenuDao;
import com.kaikeba.t31.service.AdminRoleMenuService;
import com.kaikeba.t31.service.AdminRoleUserService;
import com.kaikeba.t31.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends CrudServiceImpl<Menu> implements IMenuService {

    @Resource
    private MenuDao menuDao;

    @Autowired
    private AdminRoleMenuService adminRoleMenuService;

    @Autowired
    private AdminRoleUserService adminRoleUserService;

    @Override
    public List<Menu> listChecked(Long roleId) {
        // 查詢菜單id
        List<AdminRoleMenu> adminRoleMenus = adminRoleMenuService.getMenuByRoleId(roleId);
        if (CollectionUtils.isEmpty(adminRoleMenus)) {
            throw new RuntimeException("user not exist!");
        }
        List<Long> ids = adminRoleMenus.stream().map(adminRoleMenu -> adminRoleMenu.getMenuId()).collect(Collectors.toList());
        return menuDao.selectByIds(ids);
    }

    @Override
    public void doAssignMenu2Role(Long roleId, Long[] ids) {
        // 刪除原來的角色菜單
        adminRoleMenuService.deleteByRole(roleId);
        List<AdminRoleMenu> adminRoleMenus = Lists.newArrayListWithCapacity(ids.length);

        for (int i = 0; i < ids.length; i++) {
            AdminRoleMenu adminRoleMenu = new AdminRoleMenu();
            adminRoleMenu.setRoleId(roleId);
            adminRoleMenu.setMenuId(ids[i]);
            adminRoleMenus.add(adminRoleMenu);
        }
        adminRoleMenuService.saveBatch(adminRoleMenus);
    }

    @Override
    public List<Menu> listByUser(Long id) {
        // 查詢角色id
        List<AdminRoleUser> adminRoleUsers = adminRoleUserService.getRoleByUserId(id);
        if (CollectionUtils.isEmpty(adminRoleUsers)) {
            throw new RuntimeException("user not exist!");
        }
        List<Long> roles = adminRoleUsers.stream().map(adminRoleUser -> adminRoleUser.getRoleId()).collect(Collectors.toList());
        List<AdminRoleMenu> adminRoleMenus = adminRoleMenuService.getMenuByRoleIdList(roles);
        if (CollectionUtils.isEmpty(adminRoleMenus)) {
            throw new RuntimeException("role not exist!");
        }
        List<Long> ids = adminRoleMenus.stream().map(adminRoleMenu -> adminRoleMenu.getMenuId()).collect(Collectors.toList());
        return menuDao.selectByIds(ids);
    }
}
